package com.servlet.salary;

import com.bean.Salary;
import com.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;


@WebServlet("/admin/addSalary")
public class AddSalaryServlet extends HttpServlet {
    private double emp_month=0.05;
    private double man_month=0.01;
    private double emp_annual=0.01;
    private double tax_b=0.1;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        AdminService adminService=new AdminService();
        String id=req.getParameter("id");
        if(adminService.getEmployee(id)==null){
            req.setAttribute("Message","员工不存在，录入失败！");
            req.getRequestDispatcher("admingetfail.jsp").forward(req, resp);
            return;
        }
        String miaoshu=req.getParameter("miaoshu");
        java.util.Date d = new java.util.Date();
        Date date = new java.sql.Date(d.getTime());
        SimpleDateFormat formattery = new SimpleDateFormat("yyyy");
        SimpleDateFormat formatter = new SimpleDateFormat("MM");
        String year=formattery.format(date);
        String month = formatter.format(date);
        if (!adminService.isDouble(req.getParameter("salesVolumn"))){
            req.setAttribute("Message","销售额非数字，录入失败！");
            req.getRequestDispatcher("admingetfail.jsp").forward(req, resp);
            return;
        }
        if (!adminService.isDouble(req.getParameter("base"))){
            req.setAttribute("Message","基础工资非数字，录入失败！");
            req.getRequestDispatcher("admingetfail.jsp").forward(req, resp);
            return;
        }
        double salesVolumn=Double.parseDouble(req.getParameter("salesVolumn"));
        double base=Double.parseDouble(req.getParameter("base"));

        String name=adminService.getEmployee(id).getName();
        String dnumber=adminService.getEmployee(id).getDeptid();
        boolean ismanager=adminService.getEmployee(id).isIsmanager();

        double commision=0;
        if(ismanager) {
            commision = man_month*adminService.deptmonthsales(dnumber,year,month);
            if(month=="12")
                commision+=emp_annual*adminService.deptannualsales(dnumber,year);
        }else{
            commision = emp_month*salesVolumn;
            if(month=="12")
                commision+=emp_annual*adminService.annualsales(id,year);
        }
        double tax=tax_b*base;
        Salary salary = new Salary(99, id, name, miaoshu, date, dnumber, ismanager, base, salesVolumn, commision, tax, 0);
        salary.setSalary();
        adminService.addSalary(salary);
        req.setAttribute("Message","录入成功！");
        req.getRequestDispatcher("adminaddsalary.jsp").forward(req, resp);
    }
}
